import { defineStore } from "pinia";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

// 创建 Axios 实例（全局请求工具，可抽离）
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000,
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${localStorage.getItem("token")}`,
  },
});

// 请求/响应拦截器
request.interceptors.request.use(
  (config) => config,
  (error) => {
    ElMessage.error("请求失败，请检查网络");
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  (res) => {
    if (res.data.code !== 200) {
      ElMessage.error(res.data.message || "操作失败");
      return Promise.reject(res.data);
    }
    return res.data.data;
  },
  (error) => {
    if (error.response?.status === 401) {
      ElMessageBox.confirm("登录已过期，请重新登录", "提示", {
        confirmButtonText: "重新登录",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        localStorage.removeItem("token");
        localStorage.removeItem("isLogin");
        window.location.href = "/login";
      });
    } else {
      ElMessage.error("服务器错误，请稍后重试");
    }
    return Promise.reject(error);
  }
);

export const useAttendanceStore = defineStore("attendance", {
  state: () => ({
    clockRecords: [], // 打卡记录（缓存）
    loading: false, // 全局加载状态
    todayClockStatus: {
      checkIn: false, // 今日是否签到
      checkOut: false, // 今日是否签退
    },
  }),
  getters: {
    // 今日签到记录
    todayCheckInRecord: (state) => {
      const today = new Date().toLocaleDateString();
      return state.clockRecords.find(
        (item) =>
          new Date(item.date).toLocaleDateString() === today &&
          item.type === "上班"
      );
    },
    // 今日签退记录
    todayCheckOutRecord: (state) => {
      const today = new Date().toLocaleDateString();
      return state.clockRecords.find(
        (item) =>
          new Date(item.date).toLocaleDateString() === today &&
          item.type === "下班"
      );
    },
    // 今日是否完成全天打卡（签到+签退）
    isFullCheckedToday: (state) => {
      return state.todayClockStatus.checkIn && state.todayClockStatus.checkOut;
    },
  },
  actions: {
    // 1. 查询打卡记录（缓存+筛选）
    async fetchClockRecords(params = {}) {
      this.loading = true;
      try {
        const data = await request.get("/api/attendance/records", { params });
        this.clockRecords = data || [];
        // 更新今日打卡状态（签到/签退）
        this.updateTodayClockStatus();
      } catch (error) {
        console.error("查询打卡记录失败：", error);
        this.clockRecords = [];
        this.todayClockStatus = { checkIn: false, checkOut: false };
      } finally {
        this.loading = false;
      }
    },

    // 2. 提交打卡（根据类型选择接口）
    async submitClock(formData) {
      const { type, time, remark } = formData;
      // 校验打卡顺序：必须先签到才能签退
      if (type === "下班" && !this.todayClockStatus.checkIn) {
        ElMessage.warning("请先完成上班签到，再进行下班签退");
        return false;
      }
      // 校验重复打卡
      if (
        (type === "上班" && this.todayClockStatus.checkIn) ||
        (type === "下班" && this.todayClockStatus.checkOut)
      ) {
        ElMessage.warning(
          `今日已完成${type === "上班" ? "签到" : "签退"}，无需重复打卡`
        );
        return false;
      }

      const loading = ElMessage({
        message: `${type === "上班" ? "签到" : "签退"}中...`,
        type: "loading",
        duration: 0,
      });

      try {
        // 构造统一参数（后端两个接口需支持相同参数格式）
        const submitData = {
          clockTime: time.toISOString(), // 打卡时间（ISO格式）
          remark: remark || "", // 备注（可选）
        };

        // 根据打卡类型选择接口
        if (type === "上班") {
          await request.post("/attendance/checkIn", submitData); // 签到接口
          ElMessage.success("上班签到成功！");
        } else {
          await request.post("/attendance/checkOut", submitData); // 签退接口
          ElMessage.success("下班签退成功！");
        }

        // 重新查询记录，更新状态
        await this.fetchClockRecords();
        return true;
      } catch (error) {
        console.error(`${type === "上班" ? "签到" : "签退"}失败：`, error);
        ElMessage.error(`${type === "上班" ? "签到" : "签退"}失败，请稍后重试`);
        return false;
      } finally {
        loading.close();
      }
    },

    // 3. 更新今日打卡状态（签到/签退）
    updateTodayClockStatus() {
      this.todayClockStatus.checkIn = !!this.todayCheckInRecord;
      this.todayClockStatus.checkOut = !!this.todayCheckOutRecord;
    },

    // 4. 清除缓存（退出登录时调用）
    clearCache() {
      this.clockRecords = [];
      this.todayClockStatus = { checkIn: false, checkOut: false };
    },
  },
});
